package com.mp.approvalreq.servlet;

import com.alibaba.fastjson.JSONObject;
import com.mp.approvalreq.entity.Query;
import com.mp.approvalreq.entity.Request;
import com.mp.approvalreq.service.RequestServicePrx;
import com.mp.approvalreq.util.ApprovalUtils;
import com.mp.user.entity.User;
import com.plusmoney.exception.RpcServerLogicalException;
import com.qq.tars.client.util.ServantUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

;

/**
 * 获得某人已审批的
 *
 * @author Administrator
 */
@WebServlet("/getSomeoneApproved")
public class GetSomeoneApproved extends AbstractServlet {
    private static final long serialVersionUID = -6524473373623928868L;

    private static final Logger logger = LoggerFactory.getLogger(GetSomeoneApproved.class);

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
     throws ServletException, IOException {
        doPost(req, resp);
    }


    private void returnResult(HttpServletResponse resp, List<Request> result) throws Throwable {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("result", "0");
        jsonObject.put("res_info", "获得成功");
        jsonObject.put("data", result);

        logger.info(jsonObject.toJSONString());

        printJson(resp, jsonObject.toJSONString());
    }

    /**
     * {"page":2,"dataNum":20,"applicant":5215}		//查看自己处理的审批,applicant==contactID
     * {"page":2,"dataNum":20,"applicant":9704}	    // 查看下属的审批, applicant != contactId
     */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
     throws ServletException, IOException {
        try {
            User curUser = getReqUser(req);

            Request request = getRequest(req);
            RequestServicePrx requestServicePrx = ServantUtils.getObject(RequestServicePrx.class);
            Query query = getQuery(req, curUser, request);
            List<Request> list = requestServicePrx.getUserApproved(query);

            ApprovalUtils.replaceNewExpenseValue(list); // 替换新版本的值

            returnResult(resp, list);
        } catch (Throwable e) {
            onThrowable(req, resp, e);
        }
    }

    private Request getRequest(HttpServletRequest req) throws IOException {
        String reqBody = getContent(req);
        logger.info("json参数 {}", reqBody);

        Request request;
        try {
            request = JSONObject.parseObject(reqBody, Request.class);
            if (request == null) {
                throw new RpcServerLogicalException(1, "无输入参数");
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new RpcServerLogicalException(1, "审批内容提交失败，请稍候再试");
        }
        return request;
    }

}
